package com.mingmen.canting.gongyingshang;

import android.content.Intent;
import android.graphics.Bitmap;

import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mingmen.canting.R;
import com.mingmen.canting.adapter.SupplierDaTingAdapter;
import com.mingmen.canting.adapter.SupplierllLabelAdapter;
import com.mingmen.canting.adapter.ZhenBanSortAllLabelAdapter;
import com.mingmen.canting.adapter.ZongHelAdapter;
import com.mingmen.canting.http.callback.StringCallback;
import com.mingmen.canting.httpconfig.HttpResponse;
import com.mingmen.canting.immersionbar.ImmersionBar;
import com.mingmen.canting.model.DaTingModel;
import com.mingmen.canting.model.ShopListModel;
import com.mingmen.canting.model.SupplierAllModel;
import com.mingmen.canting.popwindow.PopupWindowCompat;
import com.mingmen.canting.refresh.ClassicsFooter;
import com.mingmen.canting.refresh.ClassicsHeader;
import com.mingmen.canting.util.GsonUtil;
import com.mingmen.canting.util.SharePreferenceUtil;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import okhttp3.Call;
import okhttp3.Response;

public class SupplierDaTingActivity extends FragmentActivity {
    @BindView(R.id.text_return)
    TextView textReturn;
    @BindView(R.id.linear_return)
    LinearLayout linearReturn;
    @BindView(R.id.text_center)
    TextView textCenter;
    @BindView(R.id.img_right)
    ImageView imgRight;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.mToolbar)
    Toolbar mToolbar;
    @BindView(R.id.recycle_list)
    RecyclerView recycle_list;
    SupplierDaTingAdapter supplierDaTingAdapter;
    List<String> dataList = new ArrayList<>();
    String token;

    List<DaTingModel.DataBean> dataBeanList = new ArrayList<>();
    @BindView(R.id.layout_zonghe)
    LinearLayout layout_zonghe;
    @BindView(R.id.arrow_first)
    ImageView arrow_first;
    int frist_Flag = 0;
    @BindView(R.id.arrow_second)
    ImageView arrow_second;
    int second_Flag = 0;

    int third_Flag = 0;
    @BindView(R.id.arrow_third)
    ImageView arrow_third;
    @BindView(R.id.layout_category)
    LinearLayout layout_category;
    @BindView(R.id.layout_allgongying)
    LinearLayout layout_allgongying;
    Bitmap bitmap;
    String categoryId = "";
    @BindView(R.id.text_gongall)
    TextView text_gongall;
    @BindView(R.id.text_pinlei)
    TextView text_pinlei;
    String cateGroy;
    @BindView(R.id.text_zonghe)
    TextView text_zonghe;

    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;
    int pageNumber = 1;
    int totalPage;
    @BindView(R.id.layout_nodata)
    LinearLayout layout_nodata;
    @BindView(R.id.layout_alldata)
    LinearLayout layout_alldata;
    List<SupplierAllModel.DataBean> supplierList = new ArrayList<>();
    String fuzzy = "0";
    String supplierId = "";

    //    text_pinlei  品类下popwindow
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_supplierdating);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        ImmersionBar.with(this).titleBar(mToolbar)
                .navigationBarColor(R.color.black).init();
        textCenter.setText("供应商大厅");
        token = (String) SharePreferenceUtil.get(this, "token", "");
        categoryId = getIntent().getStringExtra("categoryId");
        cateGroy = getIntent().getStringExtra("cateGroy");
        if (cateGroy.equals("")) {
            text_pinlei.setText("品类");
        } else {
            text_pinlei.setText(cateGroy);
        }
        bitmap = ((BitmapDrawable) getResources().getDrawable(R.mipmap.arrowdown)).getBitmap();
        Matrix matrix = new Matrix();
        matrix.setRotate(180);
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        recycle_list.setLayoutManager(new LinearLayoutManager(this));
        supplierDaTingAdapter = new SupplierDaTingAdapter(this, dataBeanList,supplierId);
        recycle_list.setAdapter(supplierDaTingAdapter);

        if (cateGroy.equals("")) {
            getData(token, fuzzy, "", third_Flag + "", pageNumber);
        } else {
            getData(token, fuzzy, categoryId, third_Flag + "", pageNumber);
        }

        supplierDaTingAdapter.setOnItemClickListener(new SupplierDaTingAdapter.OnItemClickListener() {
            @Override
            public void onItemClickListener(View view, int pos, List<DaTingModel.DataBean> myLiveList) {
                Intent intent;
//                startActivity(new Intent(SupplierDaTingActivity.this, GongYingShangActivity.class));
                switch (view.getId()) {
                    case R.id.btn_Phone:
                        intent = new Intent(Intent.ACTION_DIAL);
                        Uri data = Uri.parse("tel:" + myLiveList.get(pos).getTel());
                        intent.setData(data);
                        startActivity(intent);
                        break;
                    default:
                        intent = new Intent(SupplierDaTingActivity.this, SupplierShopActivity.class);
                        intent.putExtra("supplierId", myLiveList.get(pos).getSupplierId());
                        startActivity(intent);
                        break;
                }


            }
        });
        setPopZonghe();
        setPopSupplier();
        firstImgRotating();
        secondImgRotating();
        thirdImgRotating();
//        getCategoryCommodityList
        refreshLayout.setRefreshHeader(new ClassicsHeader(SupplierDaTingActivity.this));
        refreshLayout.setRefreshFooter(new ClassicsFooter(SupplierDaTingActivity.this));

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                dataBeanList.clear();
                pageNumber = 1;

//                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败

                getData(token, fuzzy, categoryId, supplierId + "", pageNumber);
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {


                if (pageNumber >= totalPage) {
                    Toast.makeText(SupplierDaTingActivity.this, "已到最后一页", Toast.LENGTH_SHORT).show();
                    refreshlayout.finishLoadMore(false);//传入false表示加载失败
                } else {
                    pageNumber++;
//                    getData(token, fuzzy, categoryId, supplierId + "", pageNumber);
                    HttpResponse.getSupplierList(token, fuzzy, categoryId, supplierId, pageNumber, new StringCallback(SupplierDaTingActivity.this) {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {

                            DaTingModel daTingModel = new DaTingModel();
                            daTingModel = GsonUtil.GsonToBean(s, DaTingModel.class);
                            totalPage = daTingModel.getTotalPage();
                            dataBeanList.addAll(daTingModel.getData());

                            if (dataBeanList.size() == 0) {
                                layout_nodata.setVisibility(View.VISIBLE);
                                recycle_list.setVisibility(View.GONE);
                                layout_alldata.setVisibility(View.GONE);
                            } else {
                                layout_nodata.setVisibility(View.GONE);
                                recycle_list.setVisibility(View.VISIBLE);
                                layout_alldata.setVisibility(View.VISIBLE);
                            }
                            supplierDaTingAdapter.setDataList(dataBeanList);
                        }

                        @Override
                        public void onAfter(String s, Exception e) {
                            super.onAfter(s, e);
                            refreshLayout.finishRefresh(100/*,false*/);//传入false表示刷新失败
                            refreshLayout.finishLoadMore(100/*,false*/);//传入false表示加载失败
                        }
                    });
                    refreshlayout.finishLoadMore(100/*,false*/);//传入false表示加载失败
                }


            }
        });


        HttpResponse.listSupplierCategory(new StringCallback(this) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                SupplierAllModel supplierAllModel = new SupplierAllModel();
                supplierAllModel = GsonUtil.GsonToBean(s, SupplierAllModel.class);
                supplierList.addAll(supplierAllModel.getData());
                popWindowCreate(supplierList);

            }
        });


    }

    public void getData(String token, String fuzzy, String categoryId, String supplierId, int pageNumber) {

        HttpResponse.getSupplierList(token, fuzzy, categoryId, supplierId, pageNumber, new StringCallback(this) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.d("getSupplierList",s);
                if (dataBeanList.size() > 0) {
                    dataBeanList.clear();
                }
                supplierDaTingAdapter = new SupplierDaTingAdapter(SupplierDaTingActivity.this, dataBeanList,supplierId);
                recycle_list.setAdapter(supplierDaTingAdapter);
                DaTingModel daTingModel = new DaTingModel();
                daTingModel = GsonUtil.GsonToBean(s, DaTingModel.class);
                totalPage = daTingModel.getTotalPage();
                dataBeanList.addAll(daTingModel.getData());

                if (dataBeanList.size() == 0) {
                    layout_nodata.setVisibility(View.VISIBLE);
                    recycle_list.setVisibility(View.GONE);
                    layout_alldata.setVisibility(View.GONE);
                } else {
                    layout_nodata.setVisibility(View.GONE);
                    recycle_list.setVisibility(View.VISIBLE);
                    layout_alldata.setVisibility(View.VISIBLE);
                }
                supplierDaTingAdapter.setDataList(dataBeanList);
                supplierDaTingAdapter.setOnItemClickListener(new SupplierDaTingAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClickListener(View view, int pos, List<DaTingModel.DataBean> myLiveList) {
                        Intent intent;
//                startActivity(new Intent(SupplierDaTingActivity.this, GongYingShangActivity.class));
                        switch (view.getId()) {
                            case R.id.btn_Phone:
                                intent = new Intent(Intent.ACTION_DIAL);
                                Uri data = Uri.parse("tel:" + myLiveList.get(pos).getTel());
                                intent.setData(data);
                                startActivity(intent);
                                break;
                            default:
                                intent = new Intent(SupplierDaTingActivity.this, SupplierShopActivity.class);
                                intent.putExtra("supplierId", myLiveList.get(pos).getSupplierId());
                                startActivity(intent);
                                break;
                        }


                    }
                });
            }

            @Override
            public void onAfter(String s, Exception e) {
                super.onAfter(s, e);
                refreshLayout.finishRefresh(100/*,false*/);//传入false表示刷新失败
                refreshLayout.finishLoadMore(100/*,false*/);//传入false表示加载失败
            }
        });
    }


    public void firstImgRotating() {
        if (frist_Flag == 0) {
//            arrow_first.setRotation(180);
            arrow_first.setImageBitmap(bitmap);
        } else {
            arrow_first.setImageResource(R.mipmap.arrowdown);
        }
    }

    public void secondImgRotating() {
        if (second_Flag == 0) {
//            arrow_second.setRotation(180);
            arrow_second.setImageBitmap(bitmap);
        } else {
            arrow_second.setImageResource(R.mipmap.arrowdown);
        }
    }

    public void thirdImgRotating() {
        if (third_Flag == 0) {
//            arrow_third.setRotation(180);
            arrow_third.setImageBitmap(bitmap);
        } else {
            arrow_third.setImageResource(R.mipmap.arrowdown);
        }
    }

    @OnClick({R.id.text_return, R.id.linear_return, R.id.text_center, R.id.img_right, R.id.layout_zonghe, R.id.arrow_first, R.id.layout_category, R.id.layout_allgongying})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.text_return:
                finish();
                break;
            case R.id.linear_return:
                finish();
                break;
            case R.id.text_center:
                break;
            case R.id.img_right:
                break;
            case R.id.layout_zonghe:
            case R.id.arrow_first:
              /*  if (frist_Flag == 0) {
                    frist_Flag = 1;
                    text_zonghe.setText("其他排序");
                } else {
                    frist_Flag = 0;
                    text_zonghe.setText("综合排序");
                }*/

                popZonghe.showAsDropDown(layout_zonghe);
//                Toast.makeText(this, "综合排序", Toast.LENGTH_SHORT).show();
                firstImgRotating();

                break;
            case R.id.layout_category:
             /*   if (second_Flag == 0) {
                    second_Flag = 1;
                    text_pinlei.setText("全部");
                    getData(token, frist_Flag + "", "", third_Flag + "", pageNumber);
                } else {
                    second_Flag = 0;
                    if (cateGroy.equals("")) {
                        text_pinlei.setText("全部");
                    } else {
                        text_pinlei.setText(cateGroy);
                    }

                    getData(token, frist_Flag + "", "", third_Flag + "", pageNumber);
                }*/

                popupWindow.showAsDropDown(layout_category);

                secondImgRotating();

                break;
            case R.id.layout_allgongying:

                popSupplier.showAsDropDown(layout_allgongying);

                break;
        }
    }

    PopupWindowCompat popupWindow, popZonghe, popSupplier;

    public void popWindowCreate(List<SupplierAllModel.DataBean> supplierList) {
        popupWindow = new PopupWindowCompat(SupplierDaTingActivity.this);
        View view1 = LayoutInflater.from(SupplierDaTingActivity.this).inflate(R.layout.pop_supplierdating, null);
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setContentView(view1);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());

        RecyclerView recycle_biaoqian = view1.findViewById(R.id.recycle_biaoqian);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(SupplierDaTingActivity.this, 3);
        recycle_biaoqian.setLayoutManager(gridLayoutManager);
        SupplierllLabelAdapter zhenBanSortAllLabelAdapter = new SupplierllLabelAdapter(SupplierDaTingActivity.this, supplierList);
        recycle_biaoqian.setAdapter(zhenBanSortAllLabelAdapter);
        zhenBanSortAllLabelAdapter.setDataList(supplierList);
        DividerItemDecoration divider = new DividerItemDecoration(SupplierDaTingActivity.this, DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(SupplierDaTingActivity.this, R.drawable.custom_divider));
        recycle_biaoqian.addItemDecoration(divider);
        zhenBanSortAllLabelAdapter.setOnItemClickListener(new SupplierllLabelAdapter.OnItemClickListener() {
            @Override
            public void onItemLabelClickListener(View view, int pos, List<SupplierAllModel.DataBean> myLiveList) {
                zhenBanSortAllLabelAdapter.setCheckedPosition(pos);
                categoryId = myLiveList.get(pos).getId();
                text_pinlei.setText(myLiveList.get(pos).getName());
                popupWindow.dismiss();
                dataBeanList.clear();
                getData(token, fuzzy, categoryId, supplierId, 1);

            }


        });
    }

    public void setPopZonghe() {
        popZonghe = new PopupWindowCompat(SupplierDaTingActivity.this);
        View view1 = LayoutInflater.from(SupplierDaTingActivity.this).inflate(R.layout.pop_zonghe, null);
        popZonghe.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popZonghe.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        popZonghe.setContentView(view1);
        popZonghe.setOutsideTouchable(true);
        popZonghe.setFocusable(true);
        popZonghe.setBackgroundDrawable(new BitmapDrawable());

        RecyclerView recycle_biaoqian = view1.findViewById(R.id.recycle_biaoqian);

//        GridLayoutManager gridLayoutManager = new GridLayoutManager(SupplierDaTingActivity.this, 3);
        recycle_biaoqian.setLayoutManager(new LinearLayoutManager(SupplierDaTingActivity.this));
        List<String> zonghe = new ArrayList<>();
        if (zonghe.size() > 0) {
            zonghe.clear();
        }
        zonghe.add("综合");
        zonghe.add("销量");
        zonghe.add("评分");

        ZongHelAdapter zhenBanSortAllLabelAdapter = new ZongHelAdapter(SupplierDaTingActivity.this, zonghe);
        recycle_biaoqian.setAdapter(zhenBanSortAllLabelAdapter);
        zhenBanSortAllLabelAdapter.setDataList(zonghe);
        DividerItemDecoration divider = new DividerItemDecoration(SupplierDaTingActivity.this, DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(SupplierDaTingActivity.this, R.drawable.custom_divider));
        recycle_biaoqian.addItemDecoration(divider);
        zhenBanSortAllLabelAdapter.setOnItemClickListener(new ZongHelAdapter.OnItemClickListener() {
            @Override
            public void onItemLabelClickListener(View view, int pos, List<String> myLiveList) {
                if (pos == 0) {
                    fuzzy = "0";
                } else if (pos == 1) {
                    fuzzy = "1";
                } else if (pos == 2) {
                    fuzzy = "2";
                }
                text_zonghe.setText(myLiveList.get(pos));
                popZonghe.dismiss();
                dataBeanList.clear();
//                getData(token, frist_Flag + "", "", third_Flag + "", pageNumber);
                getData(token, fuzzy, categoryId, supplierId, 1);

            }

        });
    }

    public void setPopSupplier() {
        popSupplier = new PopupWindowCompat(SupplierDaTingActivity.this);
        View view1 = LayoutInflater.from(SupplierDaTingActivity.this).inflate(R.layout.pop_zonghe, null);
        popSupplier.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popSupplier.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        popSupplier.setContentView(view1);
        popSupplier.setOutsideTouchable(true);
        popSupplier.setFocusable(true);
        popSupplier.setBackgroundDrawable(new BitmapDrawable());

        RecyclerView recycle_biaoqian = view1.findViewById(R.id.recycle_biaoqian);

//        GridLayoutManager gridLayoutManager = new GridLayoutManager(SupplierDaTingActivity.this, 3);
        recycle_biaoqian.setLayoutManager(new LinearLayoutManager(SupplierDaTingActivity.this));
        List<String> zonghe = new ArrayList<>();
        if (zonghe.size() > 0) {
            zonghe.clear();
        }
        zonghe.add("全部供应商");
        zonghe.add("合作");
        zonghe.add("推荐");
        zonghe.add("其他供应商");

        ZongHelAdapter zhenBanSortAllLabelAdapter = new ZongHelAdapter(SupplierDaTingActivity.this, zonghe);
        recycle_biaoqian.setAdapter(zhenBanSortAllLabelAdapter);
        zhenBanSortAllLabelAdapter.setDataList(zonghe);
        DividerItemDecoration divider = new DividerItemDecoration(SupplierDaTingActivity.this, DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(SupplierDaTingActivity.this, R.drawable.custom_divider));
        recycle_biaoqian.addItemDecoration(divider);
        zhenBanSortAllLabelAdapter.setOnItemClickListener(new ZongHelAdapter.OnItemClickListener() {
            @Override
            public void onItemLabelClickListener(View view, int pos, List<String> myLiveList) {
                supplierId = pos + "";
//                text_zonghe.setText(myLiveList.get(pos));
//                getData(token, frist_Flag + "", "", third_Flag + "", pageNumber);
                text_gongall.setText(myLiveList.get(pos));
                dataBeanList.clear();
                popSupplier.dismiss();
                getData(token, fuzzy, categoryId, supplierId, 1);

            }

        });
    }

    public void onEventMainThread(Integer integer) {
        if (integer == 6) {
            getData(token, fuzzy, categoryId, supplierId, 1);
        }

    }
}
